#include "precompile.h"

#include "Application.h"
#include "sys/io/Directory.h"
#include "sys/io/Path.h"
#include "workspace/IMainFrame.h"
#include "workspace/IWorkspace.h"
#include "workspace/IController.h"

Application::Application()
	:m_activeView(NULL)
{
}

Application::~Application()
{
}

vresult Application::Load()
{
	String exepath = io::Path::GetExeDirectory();
	StringArray architetureDlls;
	io::Directory::GetFiles(architetureDlls,exepath,L"*.xdll",false);
	StringArray::const_iterator itbegin = architetureDlls.begin();
	StringArray::const_iterator itend = architetureDlls.end();
	for (; itbegin != itend; ++itbegin)
	{
		if (ISFAILED(LoadComponent(itbegin->c_str())))
			return vfailed;
	}

	VRVERIFY(m_objMainframe.CreateObject(CLSID_MainFrame));
	VRVERIFY(m_objWorkspace.CreateObject(CLSID_Workspace));
	VRVERIFY(m_objAddinManager.CreateObject(CLSID_AddinManager));
	VRVERIFY(m_objController.CreateObject(CLSID_Controller));

	sys::InterfacePtr<IAddinManager> pIFAddinManager(m_objAddinManager);
	pIFAddinManager->LoadAll();

	if (ISFAILED(GetWorkspace()->Create(exepath)))
		return false;

	GdiplusUtil::Instance()->Open();

	return true;
}

void Application::Unload()
{
	GetWorkspace()->Close();
	GetAddinManager()->UnloadAll();

	GdiplusUtil::Instance()->Close();
}

IWorkspace* Application::GetWorkspace() const
{
	return sys::InterfacePtr<IWorkspace>(m_objWorkspace);
}

IMainFrame* Application::GetMainFrame() const
{
	return sys::InterfacePtr<IMainFrame>(m_objMainframe);
}

IAddinManager* Application::GetAddinManager() const
{
	return sys::InterfacePtr<IAddinManager>(m_objAddinManager);
}

IController* Application::GetController() const
{
	return sys::InterfacePtr<IController>(m_objController);
}

IView* Application::GetActiveView() const
{
	return m_activeView;
}

void Application::SetActiveView(IView* view) 
{
	m_activeView = view;
}

bool Application::IsActive() const
{
	return m_activeView!=NULL;
}